<template>
  <div class="offline-evaluation-container">
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="全部状态"
            clearable
            @change="handleStatusChange"
            class="status-select"
          >
            <el-option label="待审核" value="待审核" class="status-option" />
            <el-option label="已确认" value="已确认" class="status-option" />
            <el-option label="已拒绝" value="已拒绝" class="status-option" />
            <el-option label="已完成" value="已完成" class="status-option" />
            <!-- Potentially other statuses like '待指派' if applicable -->
          </el-select>
        </el-form-item>
        <!-- Add teacher filter if admin can see appointments for multiple teachers -->
        <!-- <el-form-item label="负责教师" v-if="isAdminOrSimilarRole">
          <el-input v-model="queryParams.teacherId" placeholder="教师ID" clearable />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table v-loading="loading" :data="appointmentList" border fit>
        <el-table-column prop="id" label="预约ID" width="80" align="center" />
        <el-table-column prop="studentName" label="学生姓名" min-width="100" align="center" />
        <el-table-column label="预约日期时间" min-width="180" align="center">
          <template #default="scope">
            {{ scope.row.appointmentDate }} {{ scope.row.appointmentTime }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="评估地点" min-width="150" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="studentNote"
          label="学生备注"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="createdAt" label="提交时间" min-width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '待审核'"
              type="primary"
              size="small"
              @click="handleReview(scope.row)"
            >
              审核
            </el-button>
            <el-button
              v-if="scope.row.status === '已确认'"
              type="success"
              size="small"
              @click="handleCreatePlan(scope.row)"
            >
              制定康复计划
            </el-button>
            <el-button
              v-if="scope.row.status === '已完成'"
              type="warning"
              size="small"
              @click="handleEditPlan(scope.row)"
            >
              修改康复计划
            </el-button>
            <el-button type="info" size="small" @click="handleViewDetails(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination-container"
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog title="审核线下评估" v-model="reviewDialogVisible" width="550px">
      <el-form :model="reviewForm" ref="reviewFormRef" label-width="100px">
        <el-form-item label="学生姓名">
          <el-input :value="currentAppointment?.studentName ?? ''" disabled />
        </el-form-item>
        <el-form-item label="审核结果" prop="approved">
          <el-radio-group v-model="reviewForm.approved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="教师备注" prop="teacherNote" v-if="reviewForm.approved">
          <el-input
            v-model="reviewForm.teacherNote"
            type="textarea"
            rows="3"
            placeholder="请输入教师备注 (可选)"
          />
        </el-form-item>
        <el-form-item label="拒绝理由" prop="rejectReason" v-if="!reviewForm.approved">
          <el-input
            v-model="reviewForm.rejectReason"
            type="textarea"
            rows="3"
            placeholder="请输入拒绝理由"
            :rules="[{ required: true, message: '拒绝时必须填写理由', trigger: 'blur' }]"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="线下预约详情"
      v-model="detailsDialogVisible"
      width="700px"
      class="report-detail-dialog"
    >
      <div v-if="currentAppointment" class="report-detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约ID">{{ currentAppointment.id }}</el-descriptions-item>
          <el-descriptions-item label="报告ID">{{
            currentAppointment.reportId
          }}</el-descriptions-item>
          <el-descriptions-item label="学生姓名">{{
            currentAppointment.studentName
          }}</el-descriptions-item>
          <el-descriptions-item label="学生ID">{{
            currentAppointment.studentId
          }}</el-descriptions-item>
          <el-descriptions-item label="预约日期">{{
            currentAppointment.appointmentDate
          }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{
            currentAppointment.appointmentTime
          }}</el-descriptions-item>
          <el-descriptions-item label="评估地点">{{
            currentAppointment.location
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentAppointment.status)">{{
              currentAppointment.status
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{
            formatDateTime(currentAppointment.createdAt)
          }}</el-descriptions-item>
          <el-descriptions-item label="学生备注" :span="2">{{
            currentAppointment.studentNote
          }}</el-descriptions-item>
          <el-descriptions-item v-if="currentAppointment.teacherNote" label="教师备注" :span="2">{{
            currentAppointment.teacherNote
          }}</el-descriptions-item>
          <el-descriptions-item v-if="currentAppointment.feedback" label="评估反馈" :span="2">{{
            currentAppointment.feedback
          }}</el-descriptions-item>
        </el-descriptions>

        <!-- 添加分隔线 -->
        <el-divider v-if="injuryImages.length > 0"></el-divider>
      </div>

      <!-- 移动伤病图片到底部 -->
      <div v-if="injuryImages.length > 0" class="injury-images-bottom">
        <div class="section-title">伤病照片 ({{ injuryImages.length }}张)</div>
        <div class="image-gallery">
          <div
            v-for="(url, index) in injuryImages"
            :key="index"
            class="image-item"
            @click="previewImage(url)"
          >
            <el-image
              :src="url"
              fit="cover"
              style="width: 100%; height: 100%"
              @error="onImageError"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
          </div>
        </div>
      </div>

      <!-- 没有图片时显示提示 -->
      <div v-else-if="currentAppointment && detailsDialogVisible" class="no-images-tip">
        <el-empty description="暂无伤病照片" :image-size="100" />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button
            v-if="currentAppointment?.status === '已完成'"
            type="primary"
            @click="handleViewPlan(currentAppointment)"
          >
            查看康复计划
          </el-button>
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览图片对话框 -->
    <el-dialog title="预览图片" v-model="previewVisible" width="800px">
      <div class="image-preview">
        <img :src="previewImageUrl" alt="Preview Image" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus' // ElMessageBox not used yet, can be added if needed
import type { FormInstance } from 'element-plus'
import {
  getOfflineAppointments,
  type OfflineAppointment,
  type AppointmentQueryParams,
  type OfflineAppointmentReviewRequest,
} from '@/api/health'
import { getCurrentUser } from '@/api/user'
import request from '@/utils/request' // 修正导入方式，使用默认导出
import { useRouter } from 'vue-router'

// Reactive states
const appointmentList = ref<OfflineAppointment[]>([])
const total = ref(0)
const loading = ref(false)
const submitting = ref(false)

const queryParams = reactive<AppointmentQueryParams>({
  current: 1,
  size: 10,
  status: '',
  // teacherId: undefined, // TODO: Determine if/how admin sets this for filtering
})

const reviewDialogVisible = ref(false)
const reviewFormRef = ref<FormInstance>()
const reviewForm = reactive<Partial<OfflineAppointmentReviewRequest>>({
  appointmentId: undefined,
  approved: true,
  teacherNote: '',
  rejectReason: '',
  teacherId: 0, // Placeholder - THIS NEEDS TO BE ADDRESSED (e.g., from logged-in user)
})

const detailsDialogVisible = ref(false)
const currentAppointment = ref<OfflineAppointment | null>(null)

// 添加当前教师ID变量
const currentTeacherId = ref<number | null>(null)

// 在script setup部分添加以下变量和方法
const injuryImages = ref<string[]>([])
const hasInjuryImages = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')

const router = useRouter()

// Fetch data
const fetchOfflineAppointments = async () => {
  loading.value = true
  try {
    const paramsToSubmit: AppointmentQueryParams = { ...queryParams }

    if (paramsToSubmit.status === '已确认') {
      paramsToSubmit.status = '已确认'
    }

    console.log('Fetching offline appointments with params:', paramsToSubmit)
    const res = await getOfflineAppointments(paramsToSubmit)
    if (res.code === 200 && res.data) {
      appointmentList.value = res.data.records || []

      appointmentList.value.forEach((item) => {
        if (item.status === '已确认') {
          item.status = '已确认'
        }
      })

      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取线下评估列表失败')
      appointmentList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取线下评估列表失败:', error)
    ElMessage.error('获取线下评估列表失败')
    appointmentList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 状态变更处理（带记忆功能）
const handleStatusChange = (value: string) => {
  // 保存到本地存储，使状态选择在页面刷新后仍然保持
  localStorage.setItem('offlineEvaluation_status', value || '')

  // 执行搜索
  handleSearch()
}

// Search and Reset
const handleSearch = () => {
  queryParams.current = 1
  fetchOfflineAppointments()
}

const resetQuery = () => {
  // 清除状态并更新本地存储
  queryParams.status = ''
  localStorage.setItem('offlineEvaluation_status', '')

  queryParams.current = 1
  // queryParams.teacherId = undefined; // Reset if used for filtering
  fetchOfflineAppointments()
}

// Pagination
const handleSizeChange = (val: number) => {
  queryParams.size = val
  fetchOfflineAppointments()
}

const handleCurrentChange = (val: number) => {
  queryParams.current = val
  fetchOfflineAppointments()
}

// Review action
const handleReview = (row: OfflineAppointment) => {
  currentAppointment.value = row
  reviewForm.appointmentId = row.id
  reviewForm.approved = true // Default to approve
  reviewForm.teacherNote = row.teacherNote || ''
  reviewForm.rejectReason = ''
  // reviewForm.teacherId = getLoggedInTeacherId(); // Example, needs actual implementation
  if (reviewForm.teacherId === undefined || reviewForm.teacherId === null) {
    console.warn('Review Form: teacherId using placeholder. Ensure it is correctly sourced.')
    reviewForm.teacherId = 0 // Default placeholder
  }
  reviewDialogVisible.value = true
}

// 初始化教师ID
const initTeacherId = async () => {
  try {
    const res = await getCurrentUser()
    if (res.code === 200 && res.data) {
      currentTeacherId.value = res.data.id
      console.log('当前登录用户ID:', currentTeacherId.value)
    } else {
      ElMessage.warning('获取用户信息失败，请重新登录')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.warning('获取用户信息失败，请重新登录')
  }
}

const submitReview = async () => {
  if (!reviewFormRef.value) return
  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      // 1. 验证拒绝时必须有理由
      if (!reviewForm.approved && !reviewForm.rejectReason) {
        ElMessage.warning('拒绝时必须填写理由')
        return
      }

      // 2. 确保teacherId是有效值（直接使用API获取的当前用户ID）
      if (!currentTeacherId.value) {
        ElMessage.warning('无法获取教师ID，请重新登录')
        return
      }

      submitting.value = true
      try {
        // 构建表单格式的提交数据
        const formData = new URLSearchParams()
        formData.append('appointmentId', reviewForm.appointmentId!.toString())
        formData.append('approved', reviewForm.approved!.toString())
        formData.append('teacherId', currentTeacherId.value.toString())

        if (reviewForm.approved && reviewForm.teacherNote) {
          formData.append('teacherNote', reviewForm.teacherNote)
        }

        if (!reviewForm.approved && reviewForm.rejectReason) {
          formData.append('rejectReason', reviewForm.rejectReason)
        }

        console.log('Review Offline Payload:', Object.fromEntries(formData)) // 调试输出

        // 使用Axios直接发送POST请求，指定内容类型为表单
        const response = await request.post('/assessment/admin/offline/review', formData, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        })

        const res = response.data // 访问响应中的data属性
        if (res.code === 200) {
          ElMessage.success('审核操作成功')
          reviewDialogVisible.value = false
          fetchOfflineAppointments() // 刷新列表
        } else {
          ElMessage.error(res.message || '审核失败')
        }
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// Complete action (renamed and repurposed)
const handleCreatePlan = (row: OfflineAppointment) => {
  if (!row.reportId) {
    ElMessage.error('未找到关联的伤病报告ID，无法制定计划。')
    return
  }
  // 跳转到制定康复计划页面，并携带 reportId
  router.push({ name: 'createPlan', params: { reportId: row.reportId.toString() } })
}

// 修改康复计划
const handleEditPlan = (row: OfflineAppointment) => {
  if (!row.reportId) {
    ElMessage.error('未找到关联的伤病报告ID，无法修改计划。')
    return
  }
  // 跳转到修改康复计划页面，携带reportId和mode=edit
  router.push({
    name: 'createPlan',
    params: { reportId: row.reportId.toString() },
    query: { mode: 'edit' },
  })
}

// 查看康复计划（只读模式）
const handleViewPlan = (row: OfflineAppointment) => {
  if (!row.reportId) {
    ElMessage.error('未找到关联的伤病报告ID，无法查看计划。')
    return
  }
  // 跳转到查看康复计划页面，携带reportId和mode=view
  router.push({
    name: 'createPlan',
    params: { reportId: row.reportId.toString() },
    query: { mode: 'view' },
  })
}

// View Details
const handleViewDetails = async (row: OfflineAppointment) => {
  currentAppointment.value = row

  // 获取伤病报告的详细信息，包括图片
  try {
    console.log('获取伤病报告详情，reportId:', row.reportId)
    const res = await request.get(`/injury/report/detail/${row.reportId}`) // res is AxiosResponse
    console.log('伤病报告详情返回数据:', res.data) // res.data is the actual report object

    const reportData = res.data // Directly use res.data as the report data

    // Check if reportData is valid (e.g., it exists and has an id)
    if (reportData && typeof reportData === 'object' && reportData.id) {
      console.log('报告数据 (OfferEvaluation):', reportData)

      const images: (string | null | undefined)[] = [
        reportData.injuryImage1,
        reportData.injuryImage2,
        reportData.injuryImage3,
        reportData.injuryImage4,
        reportData.injuryImage5,
        reportData.injuryImage6,
      ]

      injuryImages.value = images.filter(
        (url): url is string => typeof url === 'string' && url.trim() !== '',
      )
      console.log('处理后的图片URL数组 (OfferEvaluation):', injuryImages.value)

      hasInjuryImages.value = injuryImages.value.length > 0
    } else {
      console.warn('获取伤病报告详情失败或数据无效 (OfferEvaluation):', res.data)
      injuryImages.value = []
      hasInjuryImages.value = false
    }
  } catch (error) {
    console.error('获取伤病报告详情失败:', error)
    injuryImages.value = []
    hasInjuryImages.value = false
    ElMessage.error('获取伤病报告详情失败')
  }

  detailsDialogVisible.value = true
}

// 预览图片
const previewImage = (imageUrl: string) => {
  previewImageUrl.value = imageUrl
  previewVisible.value = true
}

// 图片加载错误处理
const onImageError = (e: Event) => {
  console.error('图片加载失败:', e)
  ElMessage.warning('部分图片加载失败')
}

// Helpers
const formatDateTime = (dateTimeStr: string | undefined) => {
  if (!dateTimeStr) return '-'
  try {
    const date = new Date(dateTimeStr)
    return date
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      })
      .replace(/\//g, '-')
  } catch {
    return dateTimeStr
  }
}

const getStatusTagType = (status: string | undefined) => {
  if (!status) return 'info'
  switch (status) {
    case '待审核':
      return 'warning'
    case '已确认':
      return 'primary' // Or '进行中' if applicable
    case '已完成':
      return 'success'
    case '已拒绝':
      return 'danger'
    default:
      return 'info'
  }
}

// Lifecycle hook
onMounted(() => {
  initTeacherId() // 获取用户ID

  // 从本地存储加载上次选择的状态
  const savedStatus = localStorage.getItem('offlineEvaluation_status')
  if (savedStatus !== null) {
    queryParams.status = savedStatus
  }

  fetchOfflineAppointments()
})
</script>

<style scoped>
.offline-evaluation-container {
  padding: 20px;
}
.filter-card,
.table-card {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 添加下拉框样式修复 */
.status-select {
  width: 150px;
}
.status-select :deep(.el-input__inner) {
  text-align: left;
}
.status-option {
  font-size: 14px;
  padding: 8px 12px;
}

/* General dialog styling (optional) */
.dialog-footer {
  text-align: right;
}

.image-preview {
  text-align: center;
}

.image-preview img {
  max-width: 100%;
  height: auto;
  margin: 0 auto;
}

/* 伤病图片展示样式优化 */
.report-detail-dialog {
  max-height: 80vh;
}

.report-detail-dialog :deep(.el-dialog__body) {
  max-height: 65vh;
  overflow-y: auto;
}

.report-detail-content {
  padding: 0 10px;
}

/* 伤病图片底部显示样式 */
.injury-images-bottom {
  margin-top: 20px;
  padding-top: 10px;
  padding-bottom: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 10px;
}

.image-item {
  width: 140px;
  height: 140px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #ebeef5;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px;
}

/* 没有图片时显示提示 */
.no-images-tip {
  text-align: center;
  padding: 20px;
}
</style>
